
//
//  AddProductionLineViewController.m
//  MagictoHire
//
//  Created by 锋 on 2017/12/11.
//  Copyright © 2017年 HUAYU. All rights reserved.
//

#import "AddProductionLineViewController.h"
#import "ProducePointTableViewCell.h"
#import "ProdoceJobDescriptionTableViewCell.h"
#import "AddMachineViewController.h"
#import "AddPointViewController.h"
#import "ProducePointModel.h"
#import "SelectWorkKindModel.h"
#import "AddMachineModel.h"
#import "ProduceLineKindViewController.h"
#import "MyProductionLineViewController.h"
#import "ProduceLineDetailViewController.h"
#import "ProduceMachinesModel.h"
#import "ProduceSpotsModel.h"

@interface AddProductionLineViewController ()<UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate>
{
    NSArray *productionNameArr;
    NSMutableArray *produceMachineModelArr;
    NSMutableArray *rightProduceNameArr;
    NSMutableArray *machineNumberArr;
    UILabel *dayLabel;
    UILabel *nameLabel;
    UIButton *addProducePointBtn;
    UILabel *jobNameLabel;
    UIButton *jobAddProducePointBtn;
    
    CGFloat scrollViewOffSetY;
    CGFloat remainingDistanceY;
    CGFloat beforeMigrationY;
    UILabel *produceTypeTipLabel;
    
}
@property (nonatomic, strong) UITableView *addProductionLineTableView;
@property (nonatomic, strong) SelectWorkKindModel *selectWorkKindModel;
@property (nonatomic, strong) AddMachineModel *addMachineModel;
@property (nonatomic, strong) ProduceLineKindModel *produceLineKindModel;
@end

@implementation AddProductionLineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    productionNameArr = @[@"产线名称", @"产线类型", @"场地费用"];
    
    if (_produceType == ADDPRODUCETYPE) {
        machineNumberArr = @[].mutableCopy;
        self.produceMachineNameArr = @[].mutableCopy;
        produceMachineModelArr = @[].mutableCopy;
        self.producePointNameArr = @[].mutableCopy;
        rightProduceNameArr = @[@"", @""].mutableCopy;
    } else {
        self.produceMachineNameArr = @[].mutableCopy;
        produceMachineModelArr = @[].mutableCopy;
        self.producePointNameArr = @[].mutableCopy;
        rightProduceNameArr = @[@"", @""].mutableCopy;
        machineNumberArr = @[].mutableCopy;
        for (int i = 0; i < _detailModel.machines.count; i++) {
            ProduceMachinesModel *machinesModel = _detailModel.machines[i];
            [self.produceMachineNameArr addObject:machinesModel.machine.name];
            AddMachineModel *tempModel = [[AddMachineModel alloc] init];
            tempModel.ID = machinesModel.machine.ID;
            tempModel.name = machinesModel.machine.name;
            [produceMachineModelArr addObject:tempModel];
            [machineNumberArr addObject:machinesModel.count];
        }
        for (int i = 0; i < _detailModel.spots.count; i++) {
            ProduceSpotsModel *spotsModel = _detailModel.spots[i];
            ProducePointModel *model = [[ProducePointModel alloc] init];
            model.nameStr = spotsModel.name;
            model.jobDetailStr = spotsModel.remark;
            [self.producePointNameArr addObject:model];
        }
        _produceLineKindModel = _detailModel.category;
        rightProduceNameArr[0] = _detailModel.name;
        rightProduceNameArr[1] = _detailModel.rent;
    }
    [self setupUI];
    [self setupMyProductionLineTableView];
    
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(jianpantanchu:) name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(jianpanhuishou:) name:UIKeyboardDidHideNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

- (void)setupUI {
    UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(saveProductionLine)];
    rightBtn.tintColor = [UIColor whiteColor];
    [rightBtn setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:15], UITextAttributeFont,nil] forState:UIControlStateNormal];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.rightBarButtonItem = rightBtn;
    self.navigationItem.title = self.produceType == ADDPRODUCETYPE ? @"添加产线" : [NSString stringWithFormat:@"%@详情", self.produceDetailTitle];
    self.view.backgroundColor = RGB(242, 242, 242);
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide:)];
    singleTap.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:singleTap];
}

- (void)setupMyProductionLineTableView {
    _addProductionLineTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - STA_NAV_HEIGHT - SCREER_HeiX) style:UITableViewStyleGrouped];
    _addProductionLineTableView.delegate = self;
    _addProductionLineTableView.dataSource = self;
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.000001)];
    view.backgroundColor = [UIColor whiteColor];
    _addProductionLineTableView.tableHeaderView = view;
    _addProductionLineTableView.tableFooterView = view;
    _addProductionLineTableView.backgroundColor = [UIColor whiteColor];
    _addProductionLineTableView.backgroundColor = RGB(242, 242, 242);
    _addProductionLineTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    if (@available(iOS 11.0, *)) {
        _addProductionLineTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    _addProductionLineTableView.estimatedRowHeight = 0;
    _addProductionLineTableView.estimatedSectionHeaderHeight = 0;
    _addProductionLineTableView.estimatedSectionFooterHeight = 0;
    [self.view addSubview:_addProductionLineTableView];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return productionNameArr.count;
    } else if (section == 1) {
        return _produceMachineNameArr.count + 1;
    } else if (section == 2) {
        if (_produceType==ADDPRODUCETYPE) {
            return _producePointNameArr.count + 2;
        } else {
            return _producePointNameArr.count + 1;
        }
    } else {
        return 0;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 0;
    } else {
        return 5;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.000001;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        NSString *ID = @"cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:ID];
        }
        cell.textLabel.text = productionNameArr[indexPath.row];
        if (![self.view viewWithTag:indexPath.row + 100]) {
            CGFloat width = SCREEN_WIDTH - 150;
            UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - width - 50, 0, width, 44)];
            textField.backgroundColor = [UIColor clearColor];
            textField.delegate = self;
            textField.tag = indexPath.row + 100;
            textField.font = [UIFont systemFontOfSize:15];
            textField.textAlignment = NSTextAlignmentLeft;
            textField.textColor = UIColorHexValue(0xB3B3B3);
            if (indexPath.row == 0) {
                textField.placeholder = @"请输入产线名称";
                UILabel *lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 43, SCREEN_WIDTH - 15, 1)];
                lineLabel.backgroundColor = RGB(238, 239, 238);
                [cell.contentView addSubview:lineLabel];
                [cell.contentView addSubview:textField];
            } else if (indexPath.row == 1) {
                if (!produceTypeTipLabel) {
                    produceTypeTipLabel = [ZCControl createLabelWithFrame:CGRectMake(SCREEN_WIDTH - width - 50, 0, width, 44) Font:15 Text:@"请选择产品类型" Color:UIColorHexValue(0xB3B3B3)];
                    [cell.contentView addSubview:produceTypeTipLabel];
                }
                if (_produceLineKindModel.name && ![_produceLineKindModel.name isKindOfClass:[NSNull class]]) {
                    produceTypeTipLabel.hidden = YES;
                }
            } else if (indexPath.row == 2) {
                if (!dayLabel) {
                    dayLabel = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 50, 0, 50, 44)];
                    dayLabel.text = @"(小时)";
                    dayLabel.textColor = UIColorHexValue(0xB3B3B3);
                    dayLabel.backgroundColor = [UIColor whiteColor];
                    dayLabel.font = [UIFont systemFontOfSize:15];
                    dayLabel.textAlignment = NSTextAlignmentLeft;
                    [cell.contentView addSubview:dayLabel];
                }
                textField.placeholder = @"请输入场地费用";
                textField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
                [cell.contentView addSubview:textField];
            }
            
        }
        if (indexPath.row == 1) {
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            UILabel *lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 43, SCREEN_WIDTH - 15, 1)];
            lineLabel.backgroundColor = RGB(238, 239, 238);
            [cell.contentView addSubview:lineLabel];
            cell.detailTextLabel.text = _produceLineKindModel.name;
            cell.detailTextLabel.textAlignment = NSTextAlignmentLeft;
            cell.detailTextLabel.textColor = UIColorHexValue(0xB3B3B3);
            cell.detailTextLabel.font = [UIFont systemFontOfSize:15];
        }
        cell.textLabel.font = [UIFont systemFontOfSize:15];
        cell.textLabel.textColor = UIColorHexValue(0x4D4D4D);
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        UITextField *textField = [cell.contentView viewWithTag:100];
        UITextField *textField2 = [cell.contentView viewWithTag:102];
        textField.text = rightProduceNameArr[0];
        textField2.text = rightProduceNameArr[1];
        
        return cell;
    } else if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            NSString *ID = @"cell1";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
            if (!cell) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
            }
            if (!nameLabel) {
                nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, SCREEN_WIDTH - 100, 44)];
                nameLabel.text = @"生产设备";
                nameLabel.textColor = UIColorHexValue(0x4D4D4D);
                nameLabel.backgroundColor = [UIColor whiteColor];
                nameLabel.font = [UIFont systemFontOfSize:16];
                nameLabel.textAlignment = NSTextAlignmentLeft;
                [cell.contentView addSubview:nameLabel];
            }
            if (!addProducePointBtn) {
                addProducePointBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 50, 0, 50, 44)];
                addProducePointBtn.backgroundColor = [UIColor whiteColor];
                [addProducePointBtn setImage:[UIImage imageNamed:@"jiahao"] forState:UIControlStateNormal];
                [addProducePointBtn addTarget:self action:@selector(onClickAddProduceMachineBtn:) forControlEvents:UIControlEventTouchUpInside];
                [cell.contentView addSubview:addProducePointBtn];
                UILabel *lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 43, SCREEN_WIDTH, 1)];
                lineLabel.backgroundColor = RGB(238, 239, 238);
                [cell.contentView addSubview:lineLabel];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            return cell;
        } else {
            ProducePointTableViewCell *cell = [[NSBundle mainBundle] loadNibNamed:@"ProducePointTableViewCell" owner:self options:nil].lastObject;

            cell.producePointNameLabel.text = _produceMachineNameArr[indexPath.row - 1];
            cell.numberTextField.textColor = UIColorHexValue(0xB3B3B3);
            cell.numberTextField.layer.borderColor = UIColorHexValue(0xB3B3B3).CGColor;
            cell.numberTextField.layer.borderWidth = 1;
            cell.numberTextField.tag = 1000 + indexPath.row;
            cell.numberTextField.delegate = self;
            cell.numberTextField.text = machineNumberArr[indexPath.row - 1];
            cell.numberTextField.keyboardType = UIKeyboardTypePhonePad;
            cell.minusBtn.layer.borderColor = UIColorHexValue(0xB3B3B3).CGColor;
            cell.minusBtn.layer.borderWidth = 1;
            cell.minusBtn.tag = indexPath.row + 500;
            [cell.minusBtn addTarget:self action:@selector(onClickMinusNumberBtn:) forControlEvents:UIControlEventTouchUpInside];
            cell.addBtn.layer.borderColor = UIColorHexValue(0xB3B3B3).CGColor;
            cell.addBtn.layer.borderWidth = 1;
            cell.addBtn.tag = indexPath.row + 500;
            [cell.addBtn addTarget:self action:@selector(onClickAddNumberBtn:) forControlEvents:UIControlEventTouchUpInside];
            cell.deleteBtn.tag = indexPath.row;
            [cell.deleteBtn addTarget:self action:@selector(deleteProduceMachine:) forControlEvents:UIControlEventTouchUpInside];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            if (indexPath.row == _produceMachineNameArr.count) {
                cell.lineLabel.hidden = YES;
            }
            
            return cell;
        }
        
    } else if (indexPath.section == 2) {
        if (indexPath.row == 0) {
            NSString *ID = @"cell2";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
            if (!cell) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
            }
            if (!jobNameLabel) {
                jobNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, SCREEN_WIDTH - 100, 44)];
                jobNameLabel.text = @"生产节点";
                jobNameLabel.textColor = UIColorHexValue(0x4D4D4D);
                jobNameLabel.backgroundColor = [UIColor whiteColor];
                jobNameLabel.font = [UIFont systemFontOfSize:16];
                jobNameLabel.textAlignment = NSTextAlignmentLeft;
                [cell.contentView addSubview:jobNameLabel];
            }
            if (!jobAddProducePointBtn) {
                jobAddProducePointBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 50, 0, 50, 44)];
                jobAddProducePointBtn.backgroundColor = [UIColor whiteColor];
                [jobAddProducePointBtn setImage:[UIImage imageNamed:@"jiahao"] forState:UIControlStateNormal];
                [jobAddProducePointBtn addTarget:self action:@selector(onClickAddProducePointBtn:) forControlEvents:UIControlEventTouchUpInside];
                [cell.contentView addSubview:jobAddProducePointBtn];
                UILabel *lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 43, SCREEN_WIDTH, 1)];
                lineLabel.backgroundColor = RGB(238, 239, 238);
                [cell.contentView addSubview:lineLabel];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            return cell;
        } else {
            ProdoceJobDescriptionTableViewCell *cell = [[NSBundle mainBundle] loadNibNamed:@"ProdoceJobDescriptionTableViewCell" owner:self options:nil].lastObject;
            cell.jobDescriptionTextField.delegate = self;
            if (indexPath.row == 1) {
                [cell.signBtn setImage:[UIImage imageNamed:@"guanlizhe"] forState:UIControlStateNormal];
                cell.jobDescriptionTextField.hidden = YES;
                cell.deleteBtn.hidden = YES;
                cell.priceLabel.hidden = YES;
                cell.nameLabel.text = @"管理者";
            } else {
                if (_producePointNameArr.count > 0) {
                    if (_produceType==ADDPRODUCETYPE) {
                        ProducePointModel *model = _producePointNameArr[indexPath.row - 2];
                        cell.nameLabel.text = model.nameStr;
                        cell.jobDescriptionTextField.text = model.jobDetailStr;
                    } else {
                        ProducePointModel *model = _producePointNameArr[indexPath.row - 1];
                        cell.nameLabel.text = model.nameStr;
                        cell.jobDescriptionTextField.text = model.jobDetailStr;
                    }
                }
                cell.priceLabel.hidden = YES;
                cell.jobDescriptionTextField.frame = CGRectMake(117*displaywidth, 0, 211*displaywidth, cell.jobDescriptionTextField.frame.size.height);
                
                cell.jobDescriptionTextField.textColor = UIColorHexValue(0xB3B3B3);
                cell.jobDescriptionTextField.delegate = self;
                cell.deleteBtn.tag = indexPath.row;
                [cell.deleteBtn addTarget:self action:@selector(deleteProducePoint:) forControlEvents:UIControlEventTouchUpInside];
                [cell.signBtn setTitle:[NSString stringWithFormat:@"%ld", indexPath.row - 1] forState:UIControlStateNormal];
                
            }
            if (indexPath.row == _producePointNameArr.count + 1) {
                cell.lineLabel.hidden = YES;
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            return cell;
        }
    } else {
        UITableViewCell *cell = [[UITableViewCell alloc] init];
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 1) {
            ProduceLineKindViewController *produceLineKindVC = [[ProduceLineKindViewController alloc] init];
            WEAKSELF;
            produceLineKindVC.produceLineKindBlock = ^(ProduceLineKindModel *produceLineKindModel) {
                weakSelf.produceLineKindModel = produceLineKindModel;
                [weakSelf.addProductionLineTableView reloadData];
            };
            [self.navigationController pushViewController:produceLineKindVC animated:YES];
        }
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)saveProductionLine {
    UITextField *textField = [self.view viewWithTag:100];
    UITextField *textField2 = [self.view viewWithTag:102];
    if ([textField.text isEqualToString:@""]) {
        [LTools showMBProgressWithText:@"请输入产线名称" addToView:self.view];
        return;
    }
    if (!_produceLineKindModel.name || [_produceLineKindModel.name isKindOfClass:[NSNull class]]|| [_produceLineKindModel.name isEqualToString:@""]) {
        [LTools showMBProgressWithText:@"请选择产线类型" addToView:self.view];
        return;
    }
    if ([textField2.text isEqualToString:@""]) {
        [LTools showMBProgressWithText:@"请输入厂地费用" addToView:self.view];
        return;
    }
    NSMutableArray *machinesArr = [NSMutableArray array];
    for (int i = 0; i < produceMachineModelArr.count; i++) {
        AddMachineModel *model = produceMachineModelArr[i];
//        ProducePointTableViewCell *cell = [_addProductionLineTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i + 1 inSection:1]];
        NSDictionary *dic = @{@"machine" : @{@"id" : model.ID}, @"count" : machineNumberArr[i]};
        [machinesArr addObject:dic];
    }
    NSMutableArray *spotsArr = [NSMutableArray array];
    if (_produceType==ADDPRODUCETYPE) {
        [spotsArr addObject:@{@"name" : @"管理者", @"remark" : @"无"}];
    }
    for (int i = 0; i < _producePointNameArr.count; i++) {
        ProducePointModel *model = _producePointNameArr[i];
        NSDictionary *dic = @{@"name" : model.nameStr, @"remark" : model.jobDetailStr};
        [spotsArr addObject:dic];
    }
    if (!machinesArr || [machinesArr isKindOfClass:[NSNull class]] || machinesArr.count==0) {
        [LTools showMBProgressWithText:@"请添加生产设备" addToView:self.view];
        return;
    }
//    if ([managerPrice isKindOfClass:[NSNull class]] || [managerPrice isEqual:@""] || !managerPrice) {
//        [LTools showMBProgressWithText:@"请输入管理者工价" addToView:self.view];
//        return;
//    }
//    if (!_producePointNameArr || [_producePointNameArr isKindOfClass:[NSNull class]]) {
//        [LTools showMBProgressWithText:@"请添加生产节点" addToView:self.view];
//        return;
//    }
//    if (!spotsArr || [spotsArr isKindOfClass:[NSNull class]]) {
//        [LTools showMBProgressWithText:@"请添加生产节点" addToView:self.view];
//        return;
//    }
    NSDictionary *dic;
    if (self.produceType == ADDPRODUCETYPE) {
        dic = @{@"name" : textField.text, @"galleryful" : @(_producePointNameArr.count), @"category" : @{@"id" : _produceLineKindModel.ID}, @"rent" : textField2.text, @"machines" : machinesArr, @"spots" : spotsArr};
    } else {
        dic = @{@"name" : textField.text, @"galleryful" : @(_producePointNameArr.count), @"category" : @{@"id" : _produceLineKindModel.ID}, @"rent" : textField2.text, @"machines" : machinesArr, @"spots" : spotsArr, @"id":_produceDetailId};
    }
    WEAKSELF;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HYBaseHandler requestSaveProductionLineParmers:dic Success:^(id obj)
     {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         if ([obj server_Getcodecheck])
         {
             NSLog(@"%@", obj);
             [LTools showMBProgressWithText:@"保存成功" addToView:weakSelf.view];
             dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                 [self.navigationController popViewControllerAnimated:YES];
             });
         }
         else
         {
             [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
         }
     } failed:^(NSError *error) {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         
     }];
}

- (void)onClickAddNumberBtn:(UIButton *)sender {
    ProducePointTableViewCell *cell = [_addProductionLineTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:sender.tag - 500 inSection:1]];
    NSInteger num = [cell.numberTextField.text integerValue];
    num ++;
    cell.numberTextField.text = [NSString stringWithFormat:@"%ld", (long)num];
    machineNumberArr[sender.tag - 500 - 1] = cell.numberTextField.text;
}

- (void)onClickMinusNumberBtn:(UIButton *)sender {
    ProducePointTableViewCell *cell = [_addProductionLineTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:sender.tag - 500 inSection:1]];
    NSInteger num = [cell.numberTextField.text integerValue];
    if (num != 1) {
        num --;
    }
    cell.numberTextField.text = [NSString stringWithFormat:@"%ld", (long)num];
    machineNumberArr[sender.tag - 500 - 1] = cell.numberTextField.text;
}

- (void)deleteProduceMachine:(UIButton *)sender {
    if (_produceMachineNameArr.count > 0) {
        [_produceMachineNameArr removeObjectAtIndex:sender.tag - 1];
        [machineNumberArr removeObjectAtIndex:sender.tag - 1];
        [produceMachineModelArr removeObjectAtIndex:sender.tag - 1];
    }
    [_addProductionLineTableView reloadData];
}

- (void)deleteProducePoint:(UIButton *)sender {
    [_producePointNameArr removeObjectAtIndex:sender.tag - 2];
    [_addProductionLineTableView reloadData];
}

- (void)onClickAddProducePointBtn:(UIButton *)sender {
    AddPointViewController *addPointVC = [[AddPointViewController alloc] init];
    WEAKSELF;
    addPointVC.addPointBlock = ^(SelectWorkKindModel *selectWorkKindModel, NSString *jobDetailStr, NSString *priceStr) {
        _selectWorkKindModel = selectWorkKindModel;
        ProducePointModel *model = [[ProducePointModel alloc] init];
        model.nameStr = jobDetailStr;
        model.jobDetailStr = priceStr;
//        model.priceStr = priceStr;
        [_producePointNameArr addObject:model];
        [weakSelf.addProductionLineTableView reloadData];
    };
    addPointVC.isAddPoint = YES;
    [self.navigationController pushViewController:addPointVC animated:YES];
}

- (void)onClickAddProduceMachineBtn:(UIButton *)sender {
    AddMachineViewController *addMachineVC = [[AddMachineViewController alloc] init];
    WEAKSELF;
    addMachineVC.addMachineBlock = ^(AddMachineModel *addMachineModel) {
        _addMachineModel = addMachineModel;
        if (_produceMachineNameArr.count > 0) {
            BOOL isSame = NO;
            NSInteger index = 0;
            for (int i = 0; i < _produceMachineNameArr.count; i++) {
                NSString *nameStr = _produceMachineNameArr[i];
                if ([nameStr isEqual:addMachineModel.name]) {
                    isSame = YES;
                    index = i;
                    break;
                } else {
                    isSame = NO;
                }
            }
            if (isSame) {
                NSInteger num = [machineNumberArr[index] integerValue];
                machineNumberArr[index] = [NSString stringWithFormat:@"%ld", num + 1];
            } else {
                [_produceMachineNameArr addObject:addMachineModel.name];
                [produceMachineModelArr addObject:addMachineModel];
                [machineNumberArr addObject:@"1"];
            }
        } else {
            [_produceMachineNameArr addObject:addMachineModel.name];
            [produceMachineModelArr addObject:addMachineModel];
            [machineNumberArr addObject:@"1"];
        }
        [weakSelf.addProductionLineTableView reloadData];
    };
    [self.navigationController pushViewController:addMachineVC animated:YES];
}

// 我们获取那个Cell是被点击的
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    /* 获取当前cell的位置*/
    /* 我们进行层次分析
     * A.superview 则是 cell
     */
    scrollViewOffSetY = _addProductionLineTableView.contentOffset.y;
    CGFloat Hieght = textField.superview.superview.frame.origin.y;
    /* 获取当前点击Cell的位置*/
    CGFloat CurrentCellY = Hieght - scrollViewOffSetY;
    /* 获取剩余高度*/
    CGFloat lastHeight = [UIScreen mainScreen].bounds.size.height - CurrentCellY-200;
    remainingDistanceY = lastHeight;
    
    
}
// 我们在获取弹出键盘的高度和在做计算差值偏移
-(void)jianpantanchu:(NSNotification*)Notification{
    NSLog(@"%@",Notification);
    /* 获取键盘的开始高度*/
    NSDictionary *userInfo = [Notification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    CGFloat keyBoardStart = keyboardRect.size.height;
    
    //    CGFloat keyBoardStart = [Notification.userInfo[@"UIKeyboardFrameBeginUserInfoKey"] CGRectValue].size.height;
    if (remainingDistanceY < keyBoardStart) {
        /* 获取差值*/
        CGFloat differenceValue = keyBoardStart -remainingDistanceY;
        beforeMigrationY = differenceValue;
        [_addProductionLineTableView setContentOffset:CGPointMake(0, differenceValue + scrollViewOffSetY) animated:YES];
    }
}

// 我们为了防止tableView不能返回原始没有被点击的位置(这是防止用户在键盘弹出的时候，在滑动而造成的混乱)
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    /* 防止错乱停止编辑*/
    [self.view endEditing:YES];
}
// 最后键盘隐藏，返回点击前的偏移
-(void)jianpanhuishou:(NSNotification*)Notification{
    NSLog(@"Hide");
    [_addProductionLineTableView setContentOffset:CGPointMake(0, scrollViewOffSetY) animated:YES];
    beforeMigrationY = 0.0;
}

-(void)keyboardHide:(UITapGestureRecognizer*)tap {
    [self.view endEditing:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField.isEditing) {
        [textField endEditing:YES];
    }
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (textField.tag == 100) {
        rightProduceNameArr[0] = textField.text;
    } else if (textField.tag == 102) {
        rightProduceNameArr[1] = textField.text;
    } else if (textField.tag >= 1001) {
        machineNumberArr[textField.tag - 1000 - 1] = textField.text;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
